﻿using System.Net.Mime;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrderApi.DTOs;

//using OrderApi.DTOs;
using OrderApi.Models;
using OrderApi.Repositories;
using OrderApi.Services;

namespace OrderApi.Controllers
{
    /// <summary>
    /// 订单管理 API 控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class OrdersController : ControllerBase
    {
        private readonly IOrderService _orderService;

        public OrdersController(IOrderService orderService)
        {
            _orderService = orderService;
        }

        /// <summary>
        /// 根据ID获取单个订单
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <returns>订单详细信息</returns>
        [HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<Order>> GetOrder(int id)
        {
            var order = await _orderService.GetOrderByIdAsync(id);
            if (order == null) return NotFound();
            return order;
        }

        /// <summary>
        /// 分页获取订单列表
        /// </summary>
        /// <param name="page">页码（默认1）</param>
        /// <param name="pageSize">每页数量（默认10）</param>
        /// <returns>分页订单列表</returns>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public async Task<ActionResult<PagedResult<Order>>> GetOrders([FromQuery] int page = 1, [FromQuery] int pageSize = 10)
        {
            return await _orderService.GetPagedOrdersAsync(page, pageSize);
        }
        /// <summary>
        /// 多条件查询订单（分页）
        /// </summary>
        /// <remarks>
        /// 根据订单编号、客户名称、订单状态、金额范围和日期范围组合查询订单列表
        /// 
        /// **查询规则：**
        /// 1. 订单编号为必填项
        /// 2. 当多个条件同时存在时，执行AND逻辑查询
        /// 
        /// **订单状态可选值：**
        /// - Created: 已创建
        /// - Processing: 处理中
        /// - Completed: 已完成
        /// - Cancelled: 已取消
        /// </remarks>
        /// <param name="parameters">查询参数</param>
        /// <returns>订单列表（分页）</returns>
        [HttpGet("query")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<ActionResult<PagedResult<Order>>> QueryOrders(
            [FromQuery] OrderQueryParameters parameters)
        {
            // 手动验证参数
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {
                return await _orderService.QueryOrdersAsync(parameters);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { error = ex.Message });
            }
        }

        /// <summary>
        /// 获取已删除的订单列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns>已删除订单列表</returns>
        [HttpGet("deleted")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public async Task<ActionResult<PagedResult<Order>>> GetDeletedOrders(
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 10)
        {
            return await _orderService.GetDeletedOrdersAsync(page, pageSize);
        }

        /// <summary>
        /// 创建新订单
        /// </summary>
        /// <param name="order">订单数据</param>
        /// <returns>创建成功的订单</returns>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<ActionResult<Order>> CreateOrder([FromBody] Order order)
        {
            var createdOrder = await _orderService.CreateOrderAsync(order);
            return CreatedAtAction(nameof(GetOrder), new { id = createdOrder.Id }, createdOrder);
        }
        /// <summary>
        /// 更新订单信息
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <param name="order">更新后的订单数据</param>
        [HttpPut("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateOrder(int id, [FromBody] Order order)
        {
            if (id != order.Id) return BadRequest();

            try
            {
                await _orderService.UpdateOrderAsync(order);
            }
            catch
            {
                if (await _orderService.GetOrderByIdAsync(id) == null)
                    return NotFound();
                throw;
            }

            return NoContent();
        }
        /// <summary>
        /// 更新订单（部分更新）
        /// </summary>
        /// <remarks>
        /// 根据订单ID或订单编号更新订单的部分字段
        /// 
        /// **更新规则：**
        /// 1. 必须提供订单ID或订单编号（二选一）
        /// 2. 只更新提供的字段，未提供的字段保持不变
        /// 
        /// **订单状态可选值：**
        /// - Created: 已创建
        /// - Processing: 处理中
        /// - Completed: 已完成
        /// - Cancelled: 已取消
        /// </remarks>
        /// <param name="dto">更新数据</param>
        /// <returns>更新后的订单</returns>
        [HttpPatch]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<Order>> UpdateOrder([FromBody] UpdateOrderDto dto)
        {
            try
            {
                return await _orderService.UpdateOrderAsync(dto);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { error = ex.Message });
            }
            catch (KeyNotFoundException ex)
            {
                return NotFound(new { error = ex.Message });
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Conflict(new
                {
                    error = "并发冲突",
                    message = "订单已被其他用户修改，请刷新后重试",
                    details = ex.Message
                });
            }
        }

        /// <summary>
        /// 简化版订单更新（返回布尔值）
        /// </summary>
        /// <remarks>
        /// 根据订单ID或订单编号更新订单的部分字段
        /// 
        /// **更新规则：**
        /// 1. 必须提供订单ID或订单编号（二选一）
        /// 2. 只更新提供的字段，未提供的字段保持不变
        /// 3. 返回布尔值表示操作是否成功
        /// 
        /// **订单状态可选值：**
        /// - Created: 已创建
        /// - Processing: 处理中
        /// - Completed: 已完成
        /// - Cancelled: 已取消
        /// </remarks>
        /// <param name="dto">更新数据</param>
        /// <returns>更新是否成功</returns>
        [HttpPut("simple-update")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<ActionResult<bool>> SimpleUpdateOrder([FromBody] SimpleUpdateOrderDto dto)
        {
            return await _orderService.SimpleUpdateOrderAsync(dto);
        }

        ///// <summary>
        ///// 删除订单
        ///// </summary>
        ///// <param name="id">要删除的订单ID</param>
        //[HttpDelete("{id}")]
        //[ProducesResponseType(StatusCodes.Status204NoContent)]
        //[ProducesResponseType(StatusCodes.Status404NotFound)]
        //public async Task<IActionResult> DeleteOrder(int id)
        //{
        //    var order = await _orderService.GetOrderByIdAsync(id);
        //    if (order == null) return NotFound();

        //    await _orderService.DeleteOrderAsync(id);
        //    return NoContent();
        //}

        /// <summary>
        /// 假删除订单
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <returns>操作结果</returns>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> DeleteOrder(int id)
        {
            var result = await _orderService.SoftDeleteOrderAsync(id);
            if (result)
            {
                return NoContent();
            }
            return NotFound();
        }

        /// <summary>
        /// 导出订单数据到Excel
        /// </summary>
        /// <returns>Excel文件流</returns>
        [HttpGet("export")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [Produces("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")]
        public async Task<IActionResult> ExportOrders()
        {
            var excelBytes = await _orderService.ExportOrdersToExcelAsync();

            // 处理中文文件名编码
            var filename = $"订单列表_{DateTime.Now:yyyyMMdd}.xlsx";
            var contentDisposition = EncodeFilename(filename);

            Response.Headers.Add("Content-Disposition", contentDisposition);
            return File(excelBytes,
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
        private string EncodeFilename(string filename)
        {
            var contentDisposition = new ContentDisposition
            {
                FileName = filename
            };

            return contentDisposition.ToString();
        }
    }
}